package com.qiwx.pigeon.activity;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.avast.android.dialogs.iface.IListDialogListener;
import com.qiwx.pigeon.R;
import com.qiwx.pigeon.Utils.DBSqlUtil;
import com.qiwx.pigeon.Utils.MyToast;
import com.qiwx.pigeon.Utils.NumberUtil;
import com.qiwx.pigeon.activity.manager.CageManagerActivity;
import com.qiwx.pigeon.activity.query.LayEggRecordActivity;
import com.qiwx.pigeon.adapter.query.CageAdapter;
import com.qiwx.pigeon.app.AppContext;
import com.qiwx.pigeon.base.BaseFragment;
import com.qiwx.pigeon.base.BaseMVPActivity;
import com.qiwx.pigeon.data.CageStatusConfig;
import com.qiwx.pigeon.data.params.CageParam;
import com.qiwx.pigeon.data.params.QueryWareHouseParam;
import com.qiwx.pigeon.data.params.SearchParam;
import com.qiwx.pigeon.data.vo.EggLoseBean;
import com.qiwx.pigeon.data.vo.LayEggAmountBean;
import com.qiwx.pigeon.data.vo.QueryCageBean;
import com.qiwx.pigeon.data.vo.QueryFertilizedBean;
import com.qiwx.pigeon.data.vo.CageProduceBean;
import com.qiwx.pigeon.data.vo.SummaryOther;
import com.qiwx.pigeon.data.vo.WareHouseBean;
import com.qiwx.pigeon.data.vo.pageinfo.PageInfo;
import com.qiwx.pigeon.fragment.HomeFragment;
import com.qiwx.pigeon.fragment.MineFragment;
import com.qiwx.pigeon.fragment.ProduceFragment;
import com.qiwx.pigeon.fragment.QueryFragment;
import com.qiwx.pigeon.helper.DialogHelper;
import com.qiwx.pigeon.presenter.QueryCagePresenter;
import com.qiwx.pigeon.presenter.WareHousePresenter;
import com.qiwx.pigeon.viewinterface.IQueryCageView;
import com.qiwx.pigeon.viewinterface.IWareHouseView;
import com.qiwx.pigeon.widget.itemderection.LineItemDecoration;

import org.angmarch.views.NiceSpinner;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseMVPActivity<IWareHouseView, WareHousePresenter> implements RadioGroup.OnCheckedChangeListener, IListDialogListener, IWareHouseView, IQueryCageView {
    @BindView(R.id.ll_navigate_bottom)
    LinearLayout llNavigateBottom;
    @BindView(R.id.edt_search_cage_number)
    EditText edtSearchCageNumber;
    @BindView(R.id.txt_search)
    TextView txtSearch;
    @BindView(R.id.rel_cage_no_search)
    RelativeLayout relCageNoSearch;
    @BindView(R.id.llTitle)
    LinearLayout llTitle;
    @BindView(R.id.imageView)
    TextView imageView;
    @BindView(R.id.recy_search)
    RecyclerView recySearch;
    @BindView(R.id.txt_search_close)
    TextView txtSearchClose;
    @BindView(R.id.lin_search)
    LinearLayout linSearch;
    @BindView(R.id.flContent)
    FrameLayout flContent;
    @BindView(R.id.spinner_wh)
    NiceSpinner spinnerWh;
    RadioGroup bottomRG;
    private int mIndex = -1;
    LinkedList<BaseFragment> fragmentStack = new LinkedList<>();
    List<WareHouseListener> listeners = new ArrayList<>();
    List<CageProduceBean> searchList = new ArrayList<>();
    CageAdapter reachAdapter;
    QueryCagePresenter queryCagePresenter;
    public static int wh_id = 46;
    public static int wh_number = 0;
    boolean isGoCD = false;//是否跳转到查蛋fragment
    private int produce_status;


    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initAfterOnCreate() {
        //updateTables();
        initFragment();
        queryWareHouse();
        initSearchView();
    }

    private void initSearchView() {
        queryCagePresenter = new QueryCagePresenter(new WeakReference(this));
        relCageNoSearch.setBackgroundColor(getResources().getColor(R.color.transparent));
        reachAdapter = new CageAdapter(R.layout.adapter_query_cage_list_item, searchList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recySearch.setLayoutManager(linearLayoutManager);
//        int space = ScreenUtils.dip2px(getActivity(), );
        recySearch.addItemDecoration(new LineItemDecoration(1));
        recySearch.setAdapter(reachAdapter);
        reachAdapter.setICageInterface((pos, status, methodId) -> {
            onAdapterClick(pos, methodId);
        });
        linSearch.setVisibility(View.GONE);
        edtSearchCageNumber.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                edtSearchCageNumber.setCursorVisible(true);
            } else {
                // 失去焦点
                edtSearchCageNumber.setCursorVisible(false);
            }
        });
        edtSearchCageNumber.setOnTouchListener((v, event) -> {
            edtSearchCageNumber.setFocusable(true);
            edtSearchCageNumber.setFocusableInTouchMode(true);
            return false;
        });
//      initSpinner  edtCageNumber.setOnClickListener(v->{
//
//            edtCageNumber.requestFocus();
//        });
    }

    public void initSpinner(List<WareHouseBean> result) {
        List<String> houses = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            houses.add(result.get(i).getName());
        }
        if (result.size() > 0) {
            wh_id = result.get(0).getId();
            wh_number = result.get(0).getNumber();
        }
        spinnerWh.attachDataSource(houses);
        spinnerWh.setOnSpinnerItemSelectedListener((parent, view, position, id) -> {
            wh_id = AppContext.houses.get(position).getId();
            wh_number = AppContext.houses.get(position).getNumber();

            if (listeners.size() > 0) {
                for (int i = 0; i < listeners.size(); i++) {
                    WareHouseListener listener = listeners.get(i);
                    if (listener != null) {
                        listener.onSelectWareHouse(AppContext.houses.get(position));
                    }
                }

            }


        });
    }

    void onAdapterClick(int pos, int methodId) {
        switch (methodId) {
            case 0:
                addEliminate(searchList.get(pos));
                break;
            case 1:
                checkLayEggRecord(searchList.get(pos));
                break;
        }

    }

    //查看鸽笼下蛋记录表
    public void checkLayEggRecord(CageProduceBean bean) {
        Intent go = new Intent(this, LayEggRecordActivity.class);
        go.putExtra("c_id", bean.getC_id());
        go.putExtra("c_number", bean.getC_number());
        startActivity(go);

    }

    //添加鸽笼到淘汰表里
    public void addEliminate(CageProduceBean bean) {
        CageParam param = new CageParam();
        param.setWh_id(bean.getWh_id());
        param.setC_id(bean.getC_id());
        param.setC_number(bean.getC_number());
        param.setEliminate_reason("应淘汰");
        queryCagePresenter.addCageEliminate(param);
    }

    private void initFragment() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        fragmentStack.add(new HomeFragment());
        ft.add(R.id.flContent, fragmentStack.peek());
        ft.commitNow();
        mIndex = -1;
        bottomRG = (RadioGroup) findViewById(R.id.rgTools);
        bottomRG.check(R.id.rb_home_tab);
        bottomRG.setOnCheckedChangeListener(this);

    }

    //获取鸽仓信息
    public void queryWareHouse() {
        QueryWareHouseParam wareHouseParam = new QueryWareHouseParam();
        wareHouseParam.setF_id(AppContext.getFarmId(this));
        mPresenter.getHouses(wareHouseParam);
    }

    //设置鸽仓监听
    public void setWareHouseListener(WareHouseListener wareHouseListener) {
        if (wareHouseListener != null) {
            listeners.add(wareHouseListener);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_home_tab:
                setIndexSelected(0);
                break;
            case R.id.rb_produce_tab:
                setIndexSelected(1);
                break;
            case R.id.rb_query_tab:
                setIndexSelected(2);
                break;
            case R.id.rb_mine_tab:
                setIndexSelected(3);
                break;
            default:
                break;
        }
    }

    @Nullable
    public HomeFragment findHomeFragment() {
        return (HomeFragment) getSupportFragmentManager().findFragmentByTag("HomeFragment");
    }

    @Nullable
    public ProduceFragment findProduceFragment() {
        return (ProduceFragment) getSupportFragmentManager().findFragmentByTag("ProduceFragment");
    }


    @Nullable
    public QueryFragment findQueryFragment() {
        return (QueryFragment) getSupportFragmentManager().findFragmentByTag("QueryFragment");
    }


    @Nullable
    public MineFragment findMineFragment() {
        return (MineFragment) getSupportFragmentManager().findFragmentByTag("MineFragment");
    }

    private void changeFragment(FragmentTransaction ft, BaseFragment fragment) {
        if (fragmentStack.peek() != null) {
            ft.hide(fragmentStack.pop());
        }
        fragmentStack.push(fragment);
        ft.show(fragment);
//        if (fragment != null) {
//            ft.show(fragment);
//        } else {
//            ft.add(R.id.flContent, fragment, fragment.getClass().getSimpleName());
//        }
    }

    //跳转到鸽笼适配
    public void goAdjustFragment() {
        produce_status = CageStatusConfig.PRODUCE_TW;
        isGoCD = true;
//        setIndexSelected(1);
        bottomRG.check(R.id.rb_produce_tab);
        isGoCD = false;

    }

    //跳转到查蛋
    public void goCdFragment() {
        produce_status = CageStatusConfig.PRODUCE_CD;

        isGoCD = true;
//        setIndexSelected(1);
        bottomRG.check(R.id.rb_produce_tab);
        isGoCD = false;
    }

    //跳转到查崽
    public void goCzFragment() {
        produce_status = CageStatusConfig.PRODUCE_CZ;

        isGoCD = true;
//        setIndexSelected(1);
        bottomRG.check(R.id.rb_produce_tab);
        isGoCD = false;
    }


    public void setIndexSelected(int index) {
        if (mIndex == index) {
            return;
        }
        if (index == 3) {
            llTitle.setVisibility(View.GONE);
        } else {
            llTitle.setVisibility(View.VISIBLE);

        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.setCustomAnimations(R.anim.fragment_enter, R.anim.fragment_exit);
        HomeFragment homeFragment = findHomeFragment();
        ProduceFragment produceFragment = findProduceFragment();
        QueryFragment queryFragment = findQueryFragment();
        MineFragment mineFragment = findMineFragment();
        switch (index) {
            case 0:
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    ft.add(R.id.flContent, homeFragment, homeFragment.getClass().getSimpleName());
                }
                changeFragment(ft, homeFragment);
                break;
            case 1:
                if (produceFragment == null) {
                    produceFragment = new ProduceFragment();
                    if (isGoCD) {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isGoCD", true);
                        bundle.putInt("produce_status", produce_status);
                        produceFragment.setArguments(bundle);
                    }
                    ft.add(R.id.flContent, produceFragment, produceFragment.getClass().getSimpleName());
                } else {
                    if (isGoCD) {
                        produceFragment.showCheckEggFragment(produce_status);
                    }
                }
                changeFragment(ft, produceFragment);

                break;
            case 2:
                if (queryFragment == null) {
                    queryFragment = new QueryFragment();
                    ft.add(R.id.flContent, queryFragment, queryFragment.getClass().getSimpleName());
                }
                changeFragment(ft, queryFragment);
                break;
            case 3:
                if (mineFragment == null) {
                    mineFragment = new MineFragment();
                    ft.add(R.id.flContent, mineFragment, mineFragment.getClass().getSimpleName());
                }
                changeFragment(ft, mineFragment);
                break;

        }
        ft.commit();
        mIndex = index;
    }

    //去鸽笼管理
    public void goCageManager(int wh_id) {
        Intent go = new Intent(this, CageManagerActivity.class);
        go.putExtra("wh_id", wh_id);
        startActivity(go);
    }

    @Override
    public void onListItemSelected(CharSequence value, int number, int requestCode) {
        switch (requestCode) {
            case DialogHelper.CODE_SELECT_WAREHOUSE:
                if (DBSqlUtil.wareHouses.size() > number) {
                    goCageManager(DBSqlUtil.wareHouses.get(number).getId());
                }
//                String item = value.toString();
//                if (number < item.length()) {
//                    String id = item.substring(3);
//                    LogUtil.e("TAG", "id:" + id);
//                    goCageManager(Integer.valueOf(id));
//                }
                break;
        }
    }

    public void searchCage() {
        String c_number = edtSearchCageNumber.getText().toString();
        if (TextUtils.isEmpty(c_number)) {
            MyToast.showShort("鸽笼编号不能为空");
            return;
        }
        SearchParam param = new SearchParam();
        param.setWh_id(wh_id);
        param.setC_number(NumberUtil.parseInt(c_number));
        queryCagePresenter.searchCage(param);
    }

//    public void goWXDCage() {
//        startActivity(new Intent(this, WXDCageActivity.class));
//    }


    @OnClick({R.id.txt_search, R.id.txt_search_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_search:
                searchCage();
                break;
            case R.id.txt_search_close:
                linSearch.setVisibility(View.GONE);
                flContent.setVisibility(View.VISIBLE);
                edtSearchCageNumber.setText(null);
                edtSearchCageNumber.setFocusable(false);
                edtSearchCageNumber.setFocusableInTouchMode(false);
                break;
        }
    }

    @Override
    public WareHousePresenter createPresenter() {
        return new WareHousePresenter(new WeakReference<>(this));
    }


    @Override
    public void onQuerySuccess(List<WareHouseBean> result) {
        if (result != null && result.size() > 0) {
            AppContext.houses.clear();
            AppContext.houses.addAll(result);
            initSpinner(result);

            if (listeners.size() > 0) {
                for (int i = 0; i < listeners.size(); i++) {
                    WareHouseListener listener = listeners.get(i);
                    if (listener != null) {
                        listener.onSelectWareHouse(result.get(0));
                    }
                }

            }
        }

    }

    @Override
    public void onAddSuccess(WareHouseBean result) {

    }

    @Override
    public void onDeleteSuccess(WareHouseBean result) {

    }

    @Override
    public void onSearchSuccess(CageProduceBean bean) {
        searchList.clear();
        searchList.add(bean);
        reachAdapter.notifyDataSetChanged();
        linSearch.setVisibility(View.VISIBLE);
        flContent.setVisibility(View.GONE);

    }

    @Override
    public void onQueryCageSuccess(PageInfo<CageProduceBean> bean) {

    }

    @Override
    public void onQueryLayEggSuccess(List<LayEggAmountBean> data) {

    }

    @Override
    public void onQueryEggLoseSuccess(List<EggLoseBean> data) {

    }

    @Override
    public void onQueryShoujSuccess(List<QueryFertilizedBean> data) {

    }

    @Override
    public void onQueryOtherSuccess(List<SummaryOther> data) {

    }

    @Override
    public void onAddCageEliminateSuccess(int type) {
        MyToast.showShort("操作成功");

    }

    @Override
    public void onFailure(String error) {
        if ("搜索".equals(error)) {
            linSearch.setVisibility(View.GONE);
            flContent.setVisibility(View.VISIBLE);
        }

    }



    //鸽仓获取成功监听
    public interface WareHouseListener {
        void onWhSuccess(List<WareHouseBean> list);

        void onSelectWareHouse(WareHouseBean wareHouseBean);
    }
}
